<?php

namespace app\controllers;

use app\models\Category;
use app\models\ProductGetForm;
use app\models\RedisService;
use Fxp\Composer\AssetPlugin\Repository\ResolutionManager;
use Yii;
use app\models\Product;
use yii\data\ActiveDataProvider;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * ProductController implements the CRUD actions for Product model.
 */
class ProductController extends Controller
{

    public $enableCsrfValidation = false;
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    public function actionTop10(){

        $redis = new \Redis();

        $redis->connect('127.0.0.1','6379');

        $data = $redis->zrevrange('top',0,2);

        print_r($data);
    }

    public function actionWei10(){

        $redis = new \Redis();

        $redis->connect('127.0.0.1','6379');

        $data = $redis->zrange('top',0,2);

        print_r($data);
    }

    /**
     * Lists all Product models.
     * @return mixed
     */
    public function actionIndex()
    {
        $name = Yii::$app->request->get('name');
        $price = Yii::$app->request->get('price');

        $redis = new \Redis();

        $redis->connect('127.0.0.1','6379');

        $cacheData = $redis->get($this->getCacheKey());

        $data = json_decode($cacheData,true);

        if($data){
            return json_encode(['code' => 0, 'msg' => '走缓存', 'data' => $data ]);
        }

        $query = Product::find();
        if(!empty($name)){
            $query->where(['name' => $name]);
        }

        if(!empty($price)){
            $query->where(['price' => $price]);
        }


        $data = $query->asArray()->all();

        $redis->set($this->getCacheKey(),json_encode($data),30);

        return json_encode(['code' => 0, 'msg' => '不走缓存', 'data' => $data ]);

    }

    private function showJson($code, $msg, $data){
        return json_encode(['code' => $code, 'msg' => $msg, 'data' => $data ]);
    }

    /**
     * @return \Redis
     */
    private function initRedis(){

        $redis = new \Redis();

        $redis->connect('127.0.0.1','6379');

        return $redis;
    }

    private function getCacheKey(){

        $key = 'productList';
        $name = Yii::$app->request->get('name');
        $price = Yii::$app->request->get('price');

        if($name&&$price){
            return $key.$name.$price;
        }elseif($name){
            return $key.$name;
        }elseif ($price){
            return $key.$price;
        }else{
            return $key;
        }
    }

    /**
     * Displays a single Product model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
        $model = $this->findModel($id);

        $model->click_num = $model->click_num+1;
        $model->save();

        $redis = new \Redis();

        $redis->connect('127.0.0.1','6379');

        $redis->zAdd('top',$model->click_num,$id);

        return $this->showJson(0,'请求成功', $model->toArray());
    }

    /**
     * Creates a new Product model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {

        if(!Yii::$app->request->isPost){
            return $this->showJson(100,'请求失败', '只能post请求');
        }


        $redis = new \Redis();
        $redis->connect("127.0.0.1","6379");
        $lock = $redis->setnx(Yii::$app->request->post('name'),1);
        if(empty($lock)){
            return $this->showJson(100,'请求失败', "被锁");
        }

        if(Product::find()->where(['name' => Yii::$app->request->post('name')])->exists()){
            return $this->showJson(100,'请求失败', "存在");
        }

        $model = new Product();
        $model->setAttributes(Yii::$app->request->post());

        if(!$model->save()){
            return $this->showJson(100,'请求失败', $model->getErrors());
        }

        return $this->showJson(0,'请求成功',$model->id);
    }

    /**
     * Updates an existing Product model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        $model->setAttributes(Yii::$app->request->post());

        if (!$model->save()) {
            return $this->showJson(100,'请求失败', $model->getErrors());

        }

        return $this->showJson(0,'请求成功',$model->id);
    }

    /**
     * Deletes an existing Product model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Product model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Product the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Product::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }


    public function actionOrder()
    {
        $name = Yii::$app->request->get('id');


        $redis = new \Redis();
        $redis->connect("127.0.0.1","6379");

//        //自减
//        if($redis->decr($name) <=0){
//            return $this->showJson(100,'请求失败', "秒杀失败");
//        }

        //list解决问题
        if(!$redis->rpop('num1')){
            return $this->showJson(100,'请求失败', "秒杀失败");
        }

        return $this->showJson(0,'请求成功', "秒杀成功");


    }


    public function actionSearch(){

        $form = new ProductGetForm();
        $form->setAttributes(Yii::$app->request->get());

        if(!$form->validate()){

            return $this->showJson(0,'请求失败',$form->getErrors());
        }

        $redis = new \Redis();

        $redis->pconnect('127.0.0.1','6379');


        $page = Yii::$app->getRequest()->get('page');
        $size = Yii::$app->getRequest()->get('size');

        $result = $redis->get($this->getProductListKey($page,$size));

        if($result){
            return $this->showJson(0,"走缓存",json_decode($result,true));
        }


        $result = Product::find()->asArray()->offset(($page-1)*$size)->limit($size)->all();

        $redis->set($this->getProductListKey($page,$size),json_encode($result),30);

        return $this->showJson(0,"不走缓存",$result);
    }

    private function getProductListKey($page,$size){

        return 'product:'.$page.':'.$size;
    }

    public function actionTest(){
        return $this->render('test');
    }


    public function actionCategory(){


        $categoryId = Yii::$app->request->get('category_id',1);


        $result = [
            'categoryList' => Category::getTree()
        ];
        return $this->render('category',['data' => $result]);
    }
}
